<script setup lang="ts">
import { ref, watch } from 'vue'

/**
 * 登录弹窗组件
 * 用于用户登录操作
 */

interface Props {
  show: boolean
  error?: string
  success?: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  close: []
  login: [email: string, password: string, serverUrl: string]
  register: [email: string, password: string, serverUrl: string]
}>()

const email = ref('')
const password = ref('')
const serverUrl = ref('http://localhost:8000')
const isLoading = ref(false)
const isRegisterMode = ref(false)
const confirmPassword = ref('')
const errorMessage = ref('')
const successMessage = ref('')

/**
 * 监听弹窗显示状态，重置表单
 */
watch(
  () => props.show,
  (newShow) => {
    if (newShow) {
      email.value = ''
      password.value = ''
      confirmPassword.value = ''
      isLoading.value = false
      isRegisterMode.value = false
      // 从本地存储加载服务器地址
      const savedServerUrl = localStorage.getItem('linkbook-server-url')
      if (savedServerUrl) {
        serverUrl.value = savedServerUrl
      }
      // 延迟聚焦，确保DOM已渲染
      setTimeout(() => {
        const input = document.querySelector('.login-input') as HTMLInputElement
        if (input) {
          input.focus()
        }
      }, 100)
    }
  }
)

/**
 * 处理登录
 */
const handleLogin = async (): Promise<void> => {
  const trimmedEmail = email.value.trim()
  const trimmedPassword = password.value.trim()
  const trimmedServerUrl = serverUrl.value.trim()

  if (!trimmedEmail || !trimmedPassword || !trimmedServerUrl) {
    errorMessage.value = '请填写完整的登录信息'
    return
  }

  isLoading.value = true
  errorMessage.value = ''
  successMessage.value = ''

  try {
    // 保存服务器地址到本地存储
    localStorage.setItem('linkbook-server-url', trimmedServerUrl)
    emit('login', trimmedEmail, trimmedPassword, trimmedServerUrl)
  } catch (error) {
    console.error('登录失败:', error)
    errorMessage.value = '登录过程中发生错误，请稍后重试'
  } finally {
    isLoading.value = false
  }
}

/**
 * 处理注册
 */
const handleRegister = async (): Promise<void> => {
  const trimmedEmail = email.value.trim()
  const trimmedPassword = password.value.trim()
  const trimmedConfirmPassword = confirmPassword.value.trim()
  const trimmedServerUrl = serverUrl.value.trim()

  if (!trimmedEmail || !trimmedPassword || !trimmedConfirmPassword || !trimmedServerUrl) {
    errorMessage.value = '请填写完整的注册信息'
    return
  }

  if (trimmedPassword !== trimmedConfirmPassword) {
    errorMessage.value = '两次输入的密码不一致'
    return
  }

  isLoading.value = true
  errorMessage.value = ''
  successMessage.value = ''

  try {
    // 保存服务器地址到本地存储
    localStorage.setItem('linkbook-server-url', trimmedServerUrl)
    emit('register', trimmedEmail, trimmedPassword, trimmedServerUrl)
  } catch (error) {
    console.error('注册失败:', error)
    errorMessage.value = '注册过程中发生错误，请稍后重试'
  } finally {
    isLoading.value = false
  }
}

/**
 * 切换登录/注册模式
 */
const toggleMode = (): void => {
  isRegisterMode.value = !isRegisterMode.value
  confirmPassword.value = ''
}

/**
 * 关闭弹窗
 */
const handleClose = (): void => {
  email.value = ''
  password.value = ''
  confirmPassword.value = ''
  isLoading.value = false
  isRegisterMode.value = false
  emit('close')
}

/**
 * 处理键盘事件
 * @param event 键盘事件
 */
const handleKeydown = (event: KeyboardEvent): void => {
  if (event.key === 'Enter') {
    if (isRegisterMode.value) {
      handleRegister()
    } else {
      handleLogin()
    }
  } else if (event.key === 'Escape') {
    handleClose()
  }
}
</script>

<template>
  <div v-if="show" class="modal-overlay" @click="handleClose">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3 class="modal-title">{{ isRegisterMode ? '用户注册' : '用户登录' }}</h3>
        <button class="close-btn" @click="handleClose">
          <svg viewBox="0 0 24 24" width="20" height="20">
            <path
              fill="currentColor"
              d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
            />
          </svg>
        </button>
      </div>

      <div class="modal-body">
        <!-- 错误和成功消息 -->
        <div v-if="props.error || errorMessage" class="message error-message">
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M11,15H13V17H11V15M11,7H13V13H11V7M12,2C6.47,2 2,6.5 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,20A8,8 0 0,1 4,12A8,8 0 0,1 12,4A8,8 0 0,1 20,12A8,8 0 0,1 12,20Z"/>
          </svg>
          {{ props.error || errorMessage }}
        </div>
        <div v-if="props.success || successMessage" class="message success-message">
          <svg viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
          </svg>
          {{ props.success || successMessage }}
        </div>

        <div class="form-group">
          <label class="form-label">服务器地址</label>
          <input
            v-model="serverUrl"
            @keydown="handleKeydown"
            class="login-input"
            placeholder="请输入服务器地址，如：http://localhost:8000"
            :disabled="isLoading"
          />
        </div>

        <div class="form-group">
          <label class="form-label">邮箱</label>
          <input
            v-model="email"
            @keydown="handleKeydown"
            type="email"
            class="login-input"
            placeholder="请输入邮箱地址"
            :disabled="isLoading"
          />
        </div>

        <div class="form-group">
          <label class="form-label">密码</label>
          <input
            v-model="password"
            @keydown="handleKeydown"
            type="password"
            class="login-input"
            placeholder="请输入密码"
            :disabled="isLoading"
          />
        </div>

        <div v-if="isRegisterMode" class="form-group">
          <label class="form-label">确认密码</label>
          <input
            v-model="confirmPassword"
            @keydown="handleKeydown"
            type="password"
            class="login-input"
            placeholder="请再次输入密码"
            :disabled="isLoading"
          />
        </div>
      </div>

      <div class="modal-footer">
        <div class="footer-left">
          <button class="btn btn-link" @click="toggleMode" :disabled="isLoading">
            {{ isRegisterMode ? '已有账号？去登录' : '没有账号？去注册' }}
          </button>
        </div>
        <div class="footer-right">
          <button class="btn btn-cancel" @click="handleClose" :disabled="isLoading">取消</button>
          <button
             v-if="!isRegisterMode"
             class="btn btn-login"
             @click="handleLogin"
             :disabled="!email.trim() || !password.trim() || !serverUrl.trim() || isLoading"
           >
             <span v-if="isLoading" class="loading-spinner"></span>
             {{ isLoading ? '登录中...' : '登录' }}
           </button>
           <button
             v-else
             class="btn btn-register"
             @click="handleRegister"
             :disabled="!email.trim() || !password.trim() || !confirmPassword.trim() || !serverUrl.trim() || isLoading"
           >
             <span v-if="isLoading" class="loading-spinner"></span>
             {{ isLoading ? '注册中...' : '注册' }}
           </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(2px);
}

.modal-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  width: 400px;
  max-width: 90vw;
  overflow: hidden;
  animation: modalSlideIn 0.2s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #e9ecef;
}

.modal-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}

.close-btn {
  padding: 4px;
  border: none;
  background: transparent;
  border-radius: 4px;
  cursor: pointer;
  color: #6c757d;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f8f9fa;
  color: #495057;
}

.modal-body {
  padding: 20px 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group:last-child {
  margin-bottom: 0;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

.login-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  font-size: 16px;
  outline: none;
  transition:
    border-color 0.2s,
    box-shadow 0.2s;
  box-sizing: border-box;
}

.login-input:focus {
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
}

.login-input:disabled {
  background: #f8f9fa;
  color: #6c757d;
  cursor: not-allowed;
}

.login-input::placeholder {
  color: #6c757d;
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-top: 1px solid #e9ecef;
}

.footer-left {
  flex: 1;
}

.footer-right {
  display: flex;
  gap: 12px;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  min-width: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.btn-cancel {
  background: #6c757d;
  color: white;
}

.btn-cancel:hover:not(:disabled) {
  background: #5a6268;
}

.btn-login {
  background: #007bff;
  color: white;
}

.btn-login:hover:not(:disabled) {
  background: #0056b3;
}

.btn-register {
  background: #28a745;
  color: white;
}

.btn-register:hover:not(:disabled) {
  background: #1e7e34;
}

.btn-link {
  background: transparent;
  color: #007bff;
  border: none;
  padding: 8px 0;
  font-size: 14px;
  text-decoration: underline;
  cursor: pointer;
}

.btn-link:hover:not(:disabled) {
  color: #0056b3;
}

.btn-link:disabled {
  color: #6c757d;
  cursor: not-allowed;
}

.message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 16px;
  font-size: 14px;
}

.error-message {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.success-message {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.btn:disabled {
  background: #e9ecef;
  color: #6c757d;
  cursor: not-allowed;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid currentColor;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
